package com.example.student_system.controller;

import com.example.student_system.entity.Student;
import com.example.student_system.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.stream.Collectors;

@Controller
public class HomeController {

    private final StudentService studentService;

    public HomeController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping("/")
    public String home(Model model) {
        // 获取所有学生
        List<Student> allStudents = studentService.getAllStudents();
        
        // 计算总学生数
        int totalStudents = allStudents.size();
        model.addAttribute("totalStudents", totalStudents);
        
        // 计算男女生人数
        long maleCount = allStudents.stream()
                .filter(student -> "男".equals(student.getGender()))
                .count();
        long femaleCount = allStudents.stream()
                .filter(student -> "女".equals(student.getGender()))
                .count();
        model.addAttribute("maleCount", maleCount);
        model.addAttribute("femaleCount", femaleCount);
        
        // 计算班级数量
        long classCount = allStudents.stream()
                .map(Student::getClassName)
                .distinct()
                .count();
        model.addAttribute("classCount", classCount);
        
        // 获取最近添加的5个学生
        List<Student> recentStudents = allStudents.stream()
                .sorted((s1, s2) -> s2.getId().compareTo(s1.getId()))
                .limit(5)
                .collect(Collectors.toList());
        model.addAttribute("recentStudents", recentStudents);
        
        return "index";
    }
}